package com.easy.controller;

import com.easy.bean.Cart;
import com.easy.bean.User;
import com.easy.service.ICartService;
import com.easy.util.LayData;
import com.easy.util.Page;
import com.easy.util.Result;
import com.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {
    @Autowired
    ICartService cartService;


    @RequestMapping("list")
    @ResponseBody
    public LayData getList(Page page, String text,HttpSession session) {
        User user = (User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        System.out.println(user.getId());
        List<Cart> list = cartService.getList(page, text, user.getId());
        int count = cartService.getCount(text, user.getId());
        return new LayData(count,list);
    }
    @RequestMapping("delete")
    @ResponseBody
    public int delete(int productid,HttpSession session){
        User user = (User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        return cartService.delete(productid,user.getId());
    }

    @RequestMapping("add")
    @ResponseBody
    public LayData add(HttpSession session, Cart cart){
        User user=(User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        cart.setUserid(user.getId());
        return LayData.success(cartService.add(cart));
    }

    @RequestMapping("edit")
    @ResponseBody
    public int edit(Cart cart){
        return cartService.edit(cart);
    }


    @PostMapping("/updateQuantity")
    @ResponseBody
    public LayData updateQuantity(@RequestParam("productid") int productId,
                                 @RequestParam("userid") int userId,
                                 @RequestParam("count") int count) {
        Cart cart = new Cart();
        cart.setProductid(productId);
        cart.setUserid(userId);
        if(count<=0||count>100){
            return LayData.success(400,"数量不得小于1, 不得大于100");
        }
        cart.setCount(count);
        int result = cartService.edit(cart);
        return LayData.success(result);
    }

}
